/*
 * Author: Gerry Lin
 * Description:
 *      此文件用于存放downloadclient按钮对应的槽函数
 */
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QListWidgetItem>
#include <QFile>
#include <QFileDialog>
#include "loginwindow.h"
#include "downclient.h"
#include "ui_downclient.h"
#include "configfile.h"
#include "filedata_t.h"
#include "operate/download.h"

/***************************************************
 * @brief 点击 返回上级目录 按钮
 ***************************************************/
void DownClient::on_pushButtonUpperDir_clicked()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    /* 检查是否到根目录 */
    if(this->currentPath == "/") {
        QMessageBox::information(this, "提示", "已在根目录");
        return ;
    }
    QString path = this->currentPath;
    /* /aaa/bbb/ccc/ */
    path = path.mid(0, path.lastIndexOf('/'));  // 截取到倒数第一个'/'的前一个位置
    path = path.mid(0, path.lastIndexOf('/') + 1);
    this->currentPath = path;
    qDebug() << "DownClient::" << __FUNCTION__ << "To upper dir " << path << "......";
    heartbeat();
}

/***************************************************
 * @brief 点击 下载 按钮
 ***************************************************/
void DownClient::on_pushButtonDownload_clicked()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    this->downFileDataList.clear();
    QList<QListWidgetItem *> selectedItemsList = this->ui->listWidgetDir->selectedItems();
    for(int i = 0; i < selectedItemsList.size(); i++) {
        int row = this->ui->listWidgetDir->row(selectedItemsList.at(i));
        qDebug() << "DownClient::" << __FUNCTION__ <<
                    QString("row %1").arg(row);
        downFileDataList.append(this->fileDataList.at(row));
    }
    if(this->downloadTask->isDownloading() || this->downloadProcess->state() == QProcess::Running) {
        QMessageBox::critical(this, "ERROR", "A download task exists. Try again after the download is complete.");
        return ;
    }
    for(int i = 0; i < this->downFileDataList.size(); i++) {
        LOG("Downloading '%s'", this->downFileDataList.at(i).name.toLatin1().data());
    }

    if(this->settings->value(DEVELOPER_DOWNLOAD_METHOD).toInt() == 0) {

        this->downloadTask->reset();
        this->downloadTask->set(downFileDataList,
                                this->currentPath,
                                this->currentDownDir);
        Download::Status startDownlaodStatus = this->downloadTask->startDownload();
        if(startDownlaodStatus != Download::NO_ERROR) {
            QMessageBox::critical(this, "Download Error", Download::errorString(startDownlaodStatus));
            return ;
        }

    } else {

        QStringList arguments;
        QString program = QCoreApplication::applicationDirPath() + "/DownloadProcess.exe";
        arguments << this->currentPath;
        arguments << this->currentDownDir;
        for(int i = 0; i < this->downFileDataList.size(); i++) {
            file_t fileData = this->downFileDataList.at(i);
            if(fileData.isFile) {
                arguments << fileData.name;
            } else {
                qDebug().noquote() << QString("%1%2 '%3' is folder.")
                            .arg("DownClient::")
                            .arg(__FUNCTION__)
                            .arg(fileData.name);
            }
        }
        if(QFile(program).exists()) {
            this->downloadProcess->start(program, arguments);
        } else {
            QMessageBox::critical(this, "ERROR", QString("The download program does not exist.\n%1").arg(program));
            return ;
        }

    }
}
void DownClient::on_pushButtonDownload_pressed()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QTimer *timer = this->pushBtnDownCursorPressedTimer;
    if(timer->isActive()) {
        timer->stop();
    }
    timer->start(500);
}
void DownClient::on_pushButtonDownload_released()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QTimer *timer = this->pushBtnDownCursorPressedTimer;
    if(timer->isActive()) { // 松开按键的时候如果timer还处于活跃状态，判定按压500ms以内，即为短按
//        this->on_pushButtonDownload_clicked();
        timer->stop();
    } else { // 松开按键的时候如果timer处于非活跃状态，判定按压>500ms，即为长按

    }
}
void DownClient::on_pushButtonDownload_CursorEnter()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QTimer *timer = this->pushBtnDownCursorEnterTimer;
    if(timer->isActive()) {
        timer->stop();
    }
    timer->start(500);
}
/* 鼠标悬停 */
void DownClient::pushBtnDownCursorEnterTimerTimeout()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QTimer *timer = this->pushBtnDownCursorEnterTimer;
    if(timer->isActive()) {
        timer->stop();
    }
    LOG("Download directory: %s", this->settings->value(USER_DOWN_DIR).toString().toLatin1().data());
}
void DownClient::on_pushButtonDownload_CursorLeave()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QTimer *timer = this->pushBtnDownCursorEnterTimer;
    if(timer->isActive()) {
        timer->stop();
    }
}
/* 鼠标长按超时 */
void DownClient::pushBtnDownCursorPressedTimerTimeout()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    /* 超时了，即直接判定为长按 下载按钮 */
    QTimer *timer = this->pushBtnDownCursorPressedTimer;
    if(timer->isActive()) {
        timer->stop();
    }
    this->on_pushButtonSelectDownDir_clicked();
}

/***************************************************
 * @brief 点击 下载路径 按钮
 ***************************************************/
void DownClient::on_pushButtonSelectDownDir_clicked()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QString customerSelectDir;
    customerSelectDir = QFileDialog::getExistingDirectory(this,
                                                          tr("Select Download Directory"),
                                                          this->currentDownDir);
    if(customerSelectDir.length() != 0) {
        this->settings->setValue(QString(USER_DOWN_DIR), customerSelectDir);
        this->currentDownDir = customerSelectDir;
        LOG(QString("Select Directory: %1").arg(customerSelectDir).toLatin1().data());
        qDebug() << __FUNCTION__ << QString("Select Directory: %1").arg(customerSelectDir);
    } else {
        qDebug() << "Because the user did not select an available directory,"
                    " the default directory will be used.";
    }
}

/*******************************************************
 * @brief 下载完成是否运行脚本
 * @return
 *******************************************************/
void DownClient::on_checkBoxRunScript_stateChanged(int status)
{
    qDebug() << "DownClient::" << __FUNCTION__;
    qDebug() << QString("state:%1").arg(status);
    if(status == Qt::CheckState::Unchecked) {
        this->settings->setValue(QString(USER_RUN_SCRIPT), false);
    } else if (status == Qt::CheckState::Checked) {
        this->settings->setValue(QString(USER_RUN_SCRIPT), true);
        QString download_dir = this->settings->value(USER_DOWN_DIR).toString();
        QString script_name = this->settings->value(USER_SCRIPT_NAME).toString();
        QString script_path = download_dir + "/" + script_name;
        LOG("Script Path : %s", script_path.toLatin1().data());
    } else {
        return ;
    }
}

/***************************************************
 * @brief 点击 上传 按钮
 ***************************************************/
void DownClient::on_pushButtonUpload_clicked()
{
    qDebug() << "DownClient::" << __FUNCTION__;
    QStringList filenames = QFileDialog::getOpenFileNames(this,
                                                          tr("Select Upload Files"),
                                                          this->currentUpDir);
    if(filenames.size() == 0) { qDebug() << "The number of files selected is 0."; return ; }
    QString at_one_filename = filenames.at(0);
    int index = at_one_filename.lastIndexOf('/');
    if(index != -1) {
        if(at_one_filename.at(index - 1) == ':') {
            at_one_filename = at_one_filename.mid(0, index + 1);
        } else {
            at_one_filename = at_one_filename.mid(0, index);
        }
    }
    qDebug() << "first file parse dir:" << at_one_filename;
    this->settings->setValue(QString(USER_UP_DIR), at_one_filename);
    this->currentUpDir = at_one_filename;
    qDebug() << filenames;
    this->uploadTask->setUploadDir(this->currentPath);
    this->uploadTask->setFilenames(filenames);
    Upload::Status startUplaodStatus = this->uploadTask->startUpload();
    if(startUplaodStatus != Upload::NO_ERROR) {
        QMessageBox::critical(this, "Upload Error", Upload::errorString(startUplaodStatus));
        return ;
    }
}

/***************************************************
 * @brief 点击 删除 按钮
 ***************************************************/
void DownClient::on_pushButtonDelete_clicked()
{
    qDebug() << "PathDelete::" << __FUNCTION__;
    QList<file_t> deleteFileDataList;
    QList<QListWidgetItem *> selectedItemsList = this->ui->listWidgetDir->selectedItems();
    for(int i = 0; i < selectedItemsList.size(); i++) {
        int row = this->ui->listWidgetDir->row(selectedItemsList.at(i));
        qDebug() << "DownClient::" << __FUNCTION__ <<
                    QString("row %1").arg(row);
        deleteFileDataList.append(this->fileDataList.at(row));
    }
    PathDelete::Status startDeleteStatus = this->deleteTask->startPathDelete(deleteFileDataList, this->currentPath);
    if(startDeleteStatus != PathDelete::NO_ERROR) {
        QMessageBox::critical(this, "Delete Error", PathDelete::errorString(startDeleteStatus));
        return ;
    }
}
